package com.wrt.sps.mgt.task;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.wrt.sps.mgt.entity.UploadFile;
import com.wrt.sps.mgt.service.UploadFileService;

import lombok.extern.log4j.Log4j2;

/**
 * 上传文件任务
 * 
 * @author 文瑞涛
 * @date 2021年4月11日 上午9:26:16
 */
@Service
@Log4j2
public class UploadFileTask {
	
	@Resource
	private UploadFileService uploadFileService;

	/**
	 * 清理未使用的上传文件
	 * 定时：每日23点执行
	 */
	@Scheduled(cron ="0 0 23 * * *" )
    public void cleanNotUsedFile() {
		List<UploadFile> temp = uploadFileService.findNotUsedFile();
		if(!CollectionUtils.isEmpty(temp)) {
			for(UploadFile uf:temp) {
				try {
					Files.delete(new File(uf.getPath()).toPath());
				} catch (IOException e) {
					log.error(e.getMessage(), e);
				}
				uploadFileService.delete(uf.getId());
			}
		}
	}
}
